package com.example.anydo.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.example.anydo.R;
import com.example.anydo.bean.CollectionBean;
import com.example.anydo.bean.TaskBean;
import com.example.anydo.bean.UserBean;
import com.example.anydo.util.database.DatabaseHelper;
import com.example.anydo.util.pub_util.SPUtil;
import com.example.anydo.util.pub_util.Util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CollectionActivity extends AppCompatActivity {
    private ListView listView;
    private int mYear;
    private int mMonth;
    private int mDay;
    private String days;
    private String times;
    String TAG = "TimeUtil：";
    private TextView userName;

    private DatabaseHelper dbHelper;
    private int userId;

    List<Map<String,Object>> datas = new ArrayList<>();
    private SimpleAdapter adapter;
    private ArrayList<TaskBean> tasks;
    private ImageView cancel;
    private TextView tv_date;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collecion);
         cancel=(ImageView)findViewById(R.id.cl_cancel);
         listView=(ListView)findViewById(R.id.lv_task);
         userName=((TextView)findViewById(R.id.collection_user));
        tv_date=((TextView)findViewById(R.id.tv_date));


         dbHelper=new DatabaseHelper(CollectionActivity.this);
         userId= Integer.parseInt(SPUtil.getUserId(this));
         userName.setText(dbHelper.getUserNameById(userId));
        tv_date.setText(Util.getDayNowShow());


         getTaskFromDB(userId);
         initData();


        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CollectionActivity.this.finish();
            }
        });
    }

    private void initData(){
        adapter=new SimpleAdapter(this,datas,R.layout.activity_colletask,
                new String[]{"title"},new int[]{R.id.taskName});
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                TextView today = view.findViewById(R.id.today);
                TextView tomorrow = view.findViewById(R.id.tomorrow);
                TextView chooseDay = view.findViewById(R.id.chooseDay);


                final Integer taskId= tasks.get((int) id).getData().getId();
                final String toDay=Util.getDayNow();

                today.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog.Builder adBuilder =new AlertDialog.Builder(CollectionActivity.this);
                        adBuilder.setMessage("确认设置为今天吗？").setPositiveButton("确认",new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                                Boolean isChanged=dbHelper.setDateOfTask(taskId,userId,toDay);
//                                if(!isChanged){
//                                    Util.toast(CollectionActivity.this,"设置日期失败！");
//                                }
                                datas.remove(position);
                                adapter.notifyDataSetChanged();
                                Util.toast(CollectionActivity.this,"设置日期:"+toDay);
                            }
                        }).setNegativeButton("取消",new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog, int which) {}
                        });
                        AlertDialog dialog = adBuilder.create();
                        dialog.show();
                    }
                });

                tomorrow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog.Builder adBuilder=new AlertDialog.Builder(CollectionActivity.this);
                        adBuilder.setMessage("确认设置为明天吗？").setPositiveButton("确认",new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                String nexDay=Util.nextDay();
                                //Boolean isChanged=dbHelper.setDateOfTask(taskId,userId,nexDay);
//                                if(!isChanged){
//                                    Util.toast(CollectionActivity.this,"设置日期失败！");
//                                }
                                datas.remove(position);
                                adapter.notifyDataSetChanged();
                                Util.toast(CollectionActivity.this,"设置日期:"+nexDay);
                            }
                        }).setNegativeButton("取消",new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog, int which) {}
                        });
                        AlertDialog dialog = adBuilder.create();
                        dialog.show();
                    }
                });

                chooseDay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        daysChoice(taskId,position);
                    }
                });
            }
        });
    }


    private void getTaskFromDB(final Integer userId){
        final DatabaseHelper dbHelper=new DatabaseHelper(this);
        tasks =dbHelper.getWaitingTask(userId);
        //tasks =new ArrayList<>();
//        for(int i = 0; i<50; i++){
//            TaskBean.DataBean d = new TaskBean.DataBean();
//            d.setTitle("未规划任务：" + i);
//            TaskBean taskBean = new TaskBean();
//            taskBean.setData(d);
//            tasks.add(taskBean);
//        }
        if(tasks == null) tasks = new ArrayList<>();
        for (TaskBean t:tasks) {
            Map<String,Object> mp =new HashMap<>();
            mp.put("title",t.getData().getTitle());
            datas.add(mp);
        }

    }

    private class DateSetter implements DatePickerDialog.OnDateSetListener{

        private final int taskId;
        private final int position;
        public DateSetter(int taskId,int position){
            this.taskId = taskId;
            this.position = position;
        }

        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            mYear = year;
            mMonth = month;
            mDay = dayOfMonth;
            if (mMonth + 1 < 10) {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append("0").append(mMonth + 1).append("0").append(mDay).toString();
                } else {
                    days = new StringBuffer().append(mYear).append("0").append(mMonth + 1).append(mDay).toString();
                }

            } else {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append(mMonth + 1).append("0").append(mDay).toString();
                } else {
                    days = new StringBuffer().append(mYear).append(mMonth + 1).append(mDay).toString();
                }

            }
            Log.e(TAG, "onDateSet: " + days);
            dbHelper.setDateOfTask(taskId,userId,days);

            datas.remove(position);
            adapter.notifyDataSetChanged();
            Util.toast(CollectionActivity.this,"设置日期"+days);
        }
    }


    public void daysChoice(Integer taskId,int position){
        Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);
        DateSetter setter =new DateSetter(taskId,position);
        DatePickerDialog dlg = new DatePickerDialog(CollectionActivity.this,
                setter, mYear, mMonth, mDay);
        dlg.show();
    }
}
